package com.mxy.myapplication.service;

import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;

import com.mxy.myapplication.util.Util;

import java.lang.ref.WeakReference;

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class GrayService extends JobService {

  private static Myhandler myhandler;

  private static class Myhandler extends Handler {

    private WeakReference<GrayService> grayServiceWeakReference;

    private Myhandler(GrayService grayService, Handler.Callback callback) {
      super(callback);
      this.grayServiceWeakReference = new WeakReference<>(grayService);
    }
  }

  private void handleMessage(Message msg) {
    try {
      switch (msg.what) {
        case 0:
          Util.showToast(this, "Job执行了");
          this.jobFinished((JobParameters) msg.obj, false);
          break;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  @Override
  public void onCreate() {
    super.onCreate();
    myhandler = new Myhandler(this, new Handler.Callback() {
      @Override
      public boolean handleMessage(Message msg) {
        if (myhandler != null) {
          GrayService grayService = myhandler.grayServiceWeakReference.get();
          if (grayService != null) {
            grayService.handleMessage(msg);
          }
        }
        return true;
      }
    });
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
  }

  @Override
  public boolean onStartJob(JobParameters params) {
    Message message = myhandler.obtainMessage(0);
    message.obj = params;
    message.sendToTarget();
    return true;
  }

  @Override
  public boolean onStopJob(JobParameters params) {
    myhandler.removeCallbacksAndMessages(null);
    return false;
  }

}
